package com.lepu.app.fun.index.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.app.utils.LoginUtil;
import com.app.utils.ObserverConst;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.Observer;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.PopUtil;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.widget.GoogleRefreshLayout;
import com.core.lib.widget.GoogleRefreshLayout.OnLoadListener;
import com.eyzhs.app.R;
import com.lepu.app.fun.index.adapter.IndexWriterCommentAdapter;
import com.lepu.app.fun.index.bean.BeanWriter;
import com.lepu.app.fun.index.bean.BeanWriterComment;
import com.lepu.app.fun.index.bean.BeanWriterHead;
import com.lepu.app.fun.mother_circle.MotherTopicActivity;
import com.lepu.app.fun.mother_circle.bean.BeanMotherTopic;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

/**
 * 作家专栏列表
 * @author dlk
 *
 */
@SuppressLint("InflateParams")
public class IndexWriterCommentActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener,AsyncRequest, OnRefreshListener,OnLoadListener, Observer {
	
	private static final String REQUEST_DATA = "request_data";
	private static final String REQUEST_DATA_MORE = "request_data_more";
	private static final String REQUEST_REPLY = "request_reply";

	private static final int MSG_DATA_SUCCESS = 10;
	private static final int MSG_DATA_FAIL = 11;
	private static final int MSG_DATA_MORE_SUCCESS = 12;
	private static final int MSG_DATA_MORE_FAIL = 13;


	// ========================================================================
	private GoogleRefreshLayout mGoogleRefreshLayout = null;
	private ListView mDataListView = null;
	private IndexWriterCommentAdapter mDataAdapter = null;
	private ArrayList<BeanWriterComment> mDataArrayList = null;
	
	private int mCurrentPage = 1;
	private String mCurrentDate = "";
	private String ArticleID;

	public BeanWriterHead mBeanHead = null;
	
	public boolean mIsNotify = false;
	
	public static IndexWriterCommentActivity instance;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.index_writer_comment_activity);

		instance = this;
		init();
		ObserverManager.getInstance().addObserver(ObserverConst.NOTIFY_WRITER_COMMENT_CHANGE, this);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		instance = null;
		ObserverManager.getInstance().removeObserver(ObserverConst.NOTIFY_WRITER_COMMENT_CHANGE);
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}
	
	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	public static IndexWriterCommentActivity getInstance(){
		return instance;
	}

	private void showHideNoDataLayout(boolean isShow)
	{
		LinearLayout noDataLayout = (LinearLayout) findViewById(R.id.noDataLayout);
		if(noDataLayout != null)
		{
			if(isShow)
				
			{   
				mGoogleRefreshLayout.setVisibility(View.GONE);
				noDataLayout.setVisibility(View.VISIBLE);
			}else{
				mGoogleRefreshLayout.setVisibility(View.VISIBLE);
				noDataLayout.setVisibility(View.GONE);
			}
		}
	}
	
	private void showFirstLoadDataLayout(boolean isShow)
	{
		LinearLayout firstLoadDataLayout = (LinearLayout) findViewById(R.id.firstLoadDataLayout);
		if(firstLoadDataLayout != null)
		{
			if(isShow)
			{
				if(mDataArrayList == null || mDataArrayList.size() == 0)
				{
					firstLoadDataLayout.setVisibility(View.VISIBLE);
				}
				
				LinearLayout noDataLayout = (LinearLayout) findViewById(R.id.noDataLayout);
				noDataLayout.setVisibility(View.GONE);
				
			}else{
				firstLoadDataLayout.setVisibility(View.GONE);
			}
		}
	}
	
	/**
	 * 初始化方法
	 */
	@SuppressWarnings("deprecation")
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setonTopbarNewLeftLayoutListener(this);
		topbar.setTopbarTitle("评论");
		
		ArticleID = getIntent().getStringExtra("ArticleID");
		
		mDataListView = (ListView) findViewById(R.id.dataListView);
		mGoogleRefreshLayout = (GoogleRefreshLayout) findViewById(R.id.swipeLayout);
		mGoogleRefreshLayout.setOnRefreshListener(this);
		mGoogleRefreshLayout.setOnLoadListener(this);
		mGoogleRefreshLayout.setColorScheme(R.color.color_listview_refresh_1,
											R.color.color_listview_refresh_2,
											R.color.color_listview_refresh_3,
											R.color.color_listview_refresh_4);
		mDataArrayList = new ArrayList<BeanWriterComment>();
		
		LinearLayout commentLayout = (LinearLayout) findViewById(R.id.comment_layout);
		commentLayout.setOnClickListener(new ViewOnclicklistener());
		
		request(false);
		
	}
	
	class ViewOnclicklistener implements View.OnClickListener {
		private EditText editText;
		
		public ViewOnclicklistener(EditText editText){
			this.editText = editText;
		}
		
        public ViewOnclicklistener(){
		}
		@Override
		public void onClick(final View v) {
			int rid = v.getId();
			switch (rid) {
			case R.id.comment_layout:
				boolean flagLogin = LoginUtil.jumpLogin(IndexWriterCommentActivity.this);
				if (flagLogin) {
					return;
				}
				showPopSend();
				break;
			case R.id.sendText:
				if(TextUtils.isEmpty(editText.getText().toString())){
					UIHelper.showToast(IndexWriterCommentActivity.this, "请输入回复内容");
					return;
				}
				if(editText.getText().toString().length() > 500){
					UIHelper.showToast(IndexWriterCommentActivity.this, "请输入500字以内回复内容");
					return;
				}
				requestReply(editText.getText().toString());
				break;
			}
		}
	}

	//显示回复布局
	public void showPopSend() {
		View view = LayoutInflater.from(IndexWriterCommentActivity.this).inflate(R.layout.writer_comment_send_view, null);
		TextView sendText = (TextView) view.findViewById(R.id.sendText);
		EditText sendContent = (EditText) view.findViewById(R.id.sendEdit);
		sendContent.setFilters(new InputFilter[] { new InputFilter.LengthFilter(500) });
		sendText.setOnClickListener(new ViewOnclicklistener(sendContent));
		
		PopUtil.getInstance().showPopWindow(IndexWriterCommentActivity.this, null, view,Gravity.BOTTOM, null, true);
	}
	
	//请求数据
	public void request(boolean isMore) {

			String request = "";
			int page = 1;
			if (isMore) {
				request = REQUEST_DATA_MORE;
				page = (mCurrentPage + 1);
			} else {
				request = REQUEST_DATA;
				mCurrentPage = page;
			}

			String url = Setting.getWriterCommentListUrl();

			Map<String, Object> map = new HashMap<String, Object>();
			JSONObject params = new JSONObject();
			try {
				params.put("DeviceID", Setting.DEVICEID);
				params.put("ApplicationID", Setting.APPLICATIONID);
			    params.put("UserID", LoginUtil.getUserId());
			    params.put("LoginToken", LoginUtil.getLoginToken());
				

			    params.put("ArticleID", ArticleID);
				params.put("RefreshTime", mCurrentDate);
				params.put("PageIndex", page);
				params.put("PageSize", Setting.PAGE_SIZE);
				
			} catch (Exception e) {
			}
			map.put("ht", params);
			ApiClient.http_post(url, map, null, this, request, true,false,true);
		}
	
		//回复
		public void requestReply(String sendContent) {
			Map<String, Object> map = new HashMap<String, Object>();
			JSONObject params = new JSONObject();
			try {
				params.put("DeviceID", Setting.DEVICEID);
				params.put("ApplicationID", Setting.APPLICATIONID);
				params.put("UserID", LoginUtil.getUserId());
				params.put("LoginToken", LoginUtil.getLoginToken());
				
				params.put("ArticleID", ArticleID);
				params.put("QuoteCommentID", -1);
				params.put("CommentContent", sendContent);
				
			} catch (Exception e) {
			}
			map.put("ht", params);
		
			ApiClient.http_post_main(Setting.getWriterCommetnReplyUrl(), map, null, this,REQUEST_REPLY, true,false);
		}

		@SuppressLint("HandlerLeak")
		public Handler mHandler = new Handler() {
			@SuppressLint("NewApi")
			@SuppressWarnings("unchecked")
			public void handleMessage(Message msg) {

				switch (msg.what) {
				case MSG_DATA_SUCCESS:
					
					String data = (String) msg.obj;
					if (data != null ) {
						showHideNoDataLayout(false);
						mDataArrayList.clear();
						
						ArrayList<BeanWriterComment> hotList = BeanWriterComment.parseJsonHotData(data);
						mDataArrayList.addAll(hotList);
						
						ArrayList<BeanWriterComment> newList = BeanWriterComment.parseJsonNewData(data);
						mDataArrayList.addAll(newList);
						
						if(mDataArrayList.size() == 0){
							UIHelper.showToast(MotherTopicActivity.getInstance(), R.string.no_data);
		                    showHideNoDataLayout(true);
		                    
		                    //刚进来显示回复布局
							showPopSend();
		                    return;
						}
						if(mIsNotify){
							mDataAdapter.notifyDataSetChanged();
							//mDataListView.smoothScrollToPosition(hotList.size());
						}else{
							ImageView image = new ImageView(IndexWriterCommentActivity.this);
							mDataListView.addHeaderView(image);
							
							mDataAdapter = new IndexWriterCommentAdapter(IndexWriterCommentActivity.this,mDataArrayList,ArticleID,hotList.size());
							mDataListView.setAdapter(mDataAdapter);
							
							mDataListView.removeHeaderView(image);
							mIsNotify = true;
							
							//刚进来显示回复布局
							showPopSend();
						}
						
					} else {
						//
						
					}

					// 更新完后调用该方法结束刷新
					mGoogleRefreshLayout.setRefreshing(false);
					
					//第一次请求用这个
					showFirstLoadDataLayout(false);
					break;
				case MSG_DATA_FAIL:

					// 更新完后调用该方法结束刷新
					mGoogleRefreshLayout.setRefreshing(false);
					showFirstLoadDataLayout(false);
					showHideNoDataLayout(true);
					break;
				case MSG_DATA_MORE_SUCCESS:

					ArrayList<BeanWriter> dataMoreList = (ArrayList<BeanWriter>) msg.obj;
					
					if (dataMoreList != null && dataMoreList.size() > 0) {
						
						mDataAdapter.notifyDataSetChanged();

						// 加载更多数据成功，page ++
						mCurrentPage++;
					} else {
						UIHelper.showToast(MotherTopicActivity.getInstance(), R.string.no_data_more);
						mGoogleRefreshLayout.setLoadMoreFinish(true);
					}

					// 加载完后调用该方法
					mGoogleRefreshLayout.setLoading(false);
					break;
				case MSG_DATA_MORE_FAIL:

					// 加载完后调用该方法
					mGoogleRefreshLayout.setLoading(false);
					break;

				default:
					break;
				}
			};
		};

		@Override
		public void onLoad() {
			request(true);
		}

		@Override
		public void onRefresh() {
			request(false);
		}

		@Override
		public void notify(String arg0, Object arg1, Object arg2) {
			request(false);
		}

		
		@Override
		public void RequestComplete(Object object, Object data) {
			if (object.equals(REQUEST_DATA)) {
				mCurrentDate = BeanWriterHead.parseJsonDate((String) data);

				Message msg = mHandler.obtainMessage();
				msg.what = MSG_DATA_SUCCESS;
				msg.obj = (String) data;
				mHandler.sendMessage(msg);
			} else if (object.equals(REQUEST_DATA_MORE)) {
				mCurrentDate = BeanMotherTopic.parseJsonDate((String) data);
				ArrayList<BeanWriterComment> dataMoreArraylist = BeanWriterComment.parseJsonNewData((String) data);

				if (dataMoreArraylist != null && dataMoreArraylist.size() > 0) {
					mDataArrayList.addAll(dataMoreArraylist);
				}

				Message msg = mHandler.obtainMessage();
				msg.what = MSG_DATA_MORE_SUCCESS;
				msg.obj = dataMoreArraylist;
				mHandler.sendMessage(msg);
			} else if(object.equals(REQUEST_REPLY)){
				ObserverManager.getInstance().notify(ObserverConst.NOTIFY_WRITER_COMMENT_CHANGE_INFO, null, null);
				PopUtil.getInstance().dismissPopWindow();
				request(false);
			}
		}

		@Override
		public void RequestError(Object object, int errorId, String errorMessage) {
			if (object.equals(REQUEST_DATA)) {
				mHandler.sendEmptyMessage(MSG_DATA_FAIL);
			} else if (object.equals(REQUEST_DATA_MORE)) {
				mHandler.sendEmptyMessage(MSG_DATA_MORE_FAIL);
			} else if(object.equals(REQUEST_REPLY)){
				
			}
		}

}
